package com.ndood.oss.qnyun.utils;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

/**
 * QnyunOSS工具类
 */
public class QnyunOSS {
	private static Logger logger = LoggerFactory.getLogger(QnyunOSS.class);
	/**
	 * 七牛云API的Access Key
	 */
	public static final String ACCESS_KEY = PropertiesUtil.readProperty("qnyun.oss.access-key");
	/**
	 * 七牛云API的Secret Key
	 */
	private static final String SECRET_KEY = PropertiesUtil.readProperty("qnyun.oss.secret-key");
	
	/**
	 * 七牛云API的endpoint
	 */
	private static final String ENDPOINT = PropertiesUtil.readProperty("qnyun.oss.endpoint");

	/**
	 * 认证信息
	 */
	private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

	/**
	 * 懒汉，线程安全单例
	 */
	public static QnyunOSS getInstance() {
		return SingletonHolder.INSTANCE;
	}

	/**
	 * 静态内部类方式实现线程安全的懒汉单例
	 */
	private static class SingletonHolder {
		private static final QnyunOSS INSTANCE = new QnyunOSS();
	}

	/**
	 * 简单上传，使用默认策略，只需要设置上传的空间名就可以了
	 */
	public String getUpToken(String bucket) {
		return auth.uploadToken(bucket);
	}

	/**
	 * 获取bucketManager
	 */
	public BucketManager getBucketManager() {
		Zone z = Zone.autoZone();
		Configuration c = new Configuration(z);
		// 实例化一个BucketManager对象
		BucketManager bucketManager = new BucketManager(auth, c);
		return bucketManager;
	}

	/**
	 * 获取uploadManager
	 */
	public UploadManager getUploadManager() {
		// 自动识别要上传的空间(bucket)的存储区域是华东、华北、华南
		Zone z = Zone.autoZone();
		Configuration c = new Configuration(z);
		// 创建上传对象
		UploadManager uploadManager = new UploadManager(c);
		return uploadManager;
	}

	/**
	 * 根据key获取url
	 */
	public String urlFromFileKey(String bucket, String folder, String fileName) {
		return ENDPOINT+"/" + folder + fileName;
	}

	/**
	 * 删除存储对象
	 */
	public void deleteObject(String bucket, String folder, String fileName) throws Exception {
		BucketManager bucketManager = getBucketManager();
		try {
			// 调用delete方法移动文件
			bucketManager.delete(bucket, folder + fileName);
			logger.info("删除" + bucket + "下的文件" + folder + fileName + "成功！");
		} catch (Exception e) {
			logger.info("删除" + bucket + "下的文件" + folder + fileName + "失败：" + e.getMessage());
			throw new Exception(e.getMessage());
		}
	}

	/**
	 * 上传文件
	 */
	public String upload(String bucket, String folder, File file) throws Exception {
		String fileName = DateUtils.getCurrentTimestamp() + file.getName();
		UploadManager uploadManager = getUploadManager();
		try {
			// 调用put方法上传
			uploadManager.put(file, folder + fileName, getUpToken(bucket));
			// 打印返回的信息
			logger.info("上传" + bucket + "下的文件" + folder + fileName + "成功！");
			return urlFromFileKey(bucket, folder, fileName);
		} catch (Exception e) {
			logger.error("上传七牛云OSS服务器异常." + e.getMessage());
			return null;
		}
	}
	
	/**
	 * 上传文件
	 */
	public String upload(String bucket, String folder, MultipartFile file) throws Exception {
		String fileName = file.getOriginalFilename();
		UploadManager uploadManager = getUploadManager();
		try {
			// 调用put方法上传
			uploadManager.put(file.getBytes(), folder + fileName, getUpToken(bucket));
			// 打印返回的信息
			logger.info("上传" + bucket + "下的文件" + folder + fileName + "成功！");
			return urlFromFileKey(bucket, folder, fileName);
		} catch (Exception e) {
			logger.error("上传七牛云OSS服务器异常." + e.getMessage());
			return null;
		}
	}

	public static void main(String[] args) throws Exception {
		QnyunOSS oss = QnyunOSS.getInstance();
		// 1 上传图片
		String url = oss.upload("ndood", "test/", new File("C:\\Users\\Administrator\\Desktop\\111.png"));
		System.out.println(url);
		// 2 删除图片
		oss.deleteObject("ndood", "test/", "20180410160243171111.png");
	}

}
